//
//  TQQLoginButton.swift
//  SwiftLearning
//
//  Created by 黄龙 on 2024/2/1.
//

import UIKit

class TQQLoginButton: UIButton {
    private var isLoading:Bool = false
    var contentColor:UIColor = .systemGreen
    var progressColor:UIColor = .white
    private var originalWidth:CGFloat = 0
    private var originalHeight:CGFloat = 0
    private var originalRadius:CGFloat = 0
    private var originalTitle:String?
    
    private let animateScale:CGFloat = 1.2
    private var timer:Timer?
    
    deinit{
        print("deinit.loginbutton")
        if let timer = timer{
            timer.invalidate()
            self.timer = nil
        }
        destroy()
    }
    
    init(frame: CGRect,title:String) {
        super.init(frame: frame)
        originalWidth = self.bounds.width
        originalHeight = self.bounds.height
        originalTitle = title
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func pressButton(){
        if isLoading{
            cancelLogin()
        }else{
            startLogin()
        }
    }
    
    func startLogin(){
        self.isUserInteractionEnabled = false
        isLoading = true
        originalRadius = self.layer.cornerRadius
        let animation = CABasicAnimation(keyPath: "cornerRadius")
        animation.timingFunction = CAMediaTimingFunction(name: .linear)
        animation.fromValue = self.originalRadius
        let toValue = originalHeight*animateScale*0.5
        animation.toValue = toValue
        animation.duration = 0.25
        self.layer.cornerRadius = toValue
        self.layer.add(animation, forKey: "cornerRadius")
        
        UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.1, options: [.curveLinear]) {[weak self] in
//放大以适应新圆角
            if let self = self{
                self.layer.bounds = CGRect(x: 0, y: 0, width: self.originalWidth*self.animateScale, height: self.originalHeight*self.animateScale)
            }
//注意是设置bounds而不是frame,所以scale变大，是以center为中心点坐标扩张的
        } completion: { _ in
            UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.1, options: [.curveLinear]) {[weak self] in
//缩小为圆
                if let self = self{
                    let circleW = self.originalHeight*self.animateScale
                    self.layer.bounds = CGRect(x: 0, y: 0, width: circleW, height: circleW)
                    self.setTitle("", for: .normal)
                }
            } completion: {[weak self] _ in
                if let self = self{
                    let circleW = self.originalHeight*self.animateScale-10.0
                    let aniView = CircleLineLoadingView(frame: CGRect(x: 5, y: 5, width: circleW, height: circleW),lineWidth: 2.0)
                    self.addSubview(aniView)
                    aniView.tag = 1920
                    aniView.updateStrokeColor(self.progressColor)
                    aniView.startAnimate()
                    //10s后未成功，自动取消
//                    self.perform(#selector(self.cancelLogin), with: nil, afterDelay: 10.0)
                    //会导致返回时，cancelLogin如果还在等执行，从而延迟才能deinit；故要加快速度释放，需要在vc中调用loginButton.destroy()
                    //或者改用timer,则不无需在vc中调用destroy,在返回时，会立即触发deinit，从而可以在deinit进一步释放动画和timer
                    self.timer = Timer(timeInterval: 10.0, repeats: false) {[weak self] _ in
                        self?.cancelLogin()
                    }
                    if let timer = self.timer{
                        RunLoop.main.add(timer, forMode: .common)
                    }
                    
                }
            }
        }
    }
    
    @objc func cancelLogin(){
        isLoading = false
        if let aniView = self.viewWithTag(1920) as? CircleLineLoadingView{
            aniView.stopAnimation()
            aniView.removeFromSuperview()
        }
        self.layer.removeAllAnimations()
        
        UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.1, options: [.curveLinear]) {[weak self] in
//先还原为scale大小
            if let self = self{
                self.layer.bounds = CGRect(x: 0, y: 0, width: self.originalWidth*self.animateScale, height: self.originalHeight*self.animateScale)
            }
        } completion: {[weak self] _ in
            if let self = self{
                self.setTitle(self.originalTitle, for: .normal)
//还原原圆角
                let animation = CABasicAnimation(keyPath: "cornerRadius")
                animation.timingFunction = CAMediaTimingFunction(name: .linear)
                animation.fromValue = self.originalHeight*self.animateScale*0.5
                animation.toValue = self.originalRadius
                animation.duration = 0.3
                self.layer.cornerRadius = self.originalRadius
                self.layer.add(animation, forKey: "cornerRadius")
            }
            UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.1, options: [.curveLinear]) {[weak self] in
//再还原初始大小
                if let self = self{
                    self.layer.bounds = CGRect(x: 0, y: 0, width: self.originalWidth, height: self.originalHeight)
                }
            } completion: {[weak self] _ in
                if let self = self{
                    self.isUserInteractionEnabled = true //loading可以点击取消
                }
            }
        }
    }
    
    func destroy(){
        isLoading = false
        NSObject.cancelPreviousPerformRequests(withTarget: self)
        self.layer.removeAllAnimations()
        if let aniView = self.viewWithTag(1920) as? CircleLineLoadingView{
            aniView.stopAnimation()
            aniView.removeFromSuperview()
        }
        self.layer.removeAllAnimations()
    }

}
